module RootHelper

  def self.get_cache_carousels(userinfo_id)

    userinfo_id = userinfo_id.to_s

    redis = Redis.new
    list_json = redis.get("carousels_#{userinfo_id.to_s}")

    list_data = list_json.present? ? JSON.parse(list_json) : []
    if !list_data.present?
      list_data = Carousel.where(:userinfo_id => BSON::ObjectId(userinfo_id), :field_mark => {"$in" => [1, 2, 3, 4]})
      redis.set("carousels_#{userinfo_id}",list_data.to_json)
      redis.expire("carousels_#{userinfo_id}",60*10)
    else
      list_data.collect!{|u| Carousel.new(u)}
    end
    list_data
  end


  def self.get_hot_sale_products(userinfo_id)

    userinfo_id = userinfo_id.to_s

    redis = Redis.new
    list_json = redis.get("hot_sale_products_#{userinfo_id}")

    list_data = list_json.present? ? JSON.parse(list_json) : []
    if !list_data.present?

      online_state = State.online
      list_data = []

      HotSaleGood.where({:userinfo_id => BSON::ObjectId(userinfo_id)}).order_by(:orderval => :asc).each do |hot|
        product=Product.shop_id(userinfo_id).find(hot.product_id)

        next if (online_state.id.to_s!=product['state_id'].to_s)
        product["orderval"] = hot["orderval"]
        list_data << product
      end
      redis.set("hot_sale_products_#{userinfo_id}",list_data.to_json)
      redis.expire("hot_sale_products_#{userinfo_id}",60*10)
    else
      list_data.collect!{|u| Product.new(u)}
    end
    list_data
  end


  def self.refresh_location(session_id,latitude,longitude)
    redis = Redis.new
    redis.set("#{session_id}_latitude",latitude)
    redis.set("#{session_id}_longitude",longitude)
    redis.expire("#{session_id}_latitude",60*2)
    redis.expire("#{session_id}_longitude",60*2)
  end

  def self.clean_location(session_id)
    redis = Redis.new
    redis.del("#{session_id}_latitude")
    redis.del("#{session_id}_longitude")
  end

  def self.is_location_expire(session_id)
    redis = Redis.new
    latitude = redis.get("#{session_id}_latitude")
    longitude = redis.get("#{session_id}_longitude")

    Rails.logger.info "定位信息为：session_id:#{session_id},latitude:#{latitude},longitude:#{longitude}"

    latitude.present? && longitude.present?
  end

end
